 #!/usr/bin/env python3
"""
检查模型文件的状态和训练时间
"""

import sys
import os
from pathlib import Path
import pickle
import json
from datetime import datetime

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def check_model_files():
    """检查模型文件的状态"""
    print("🔍 检查模型文件状态...")
    
    model_dir = Path("backend/models/saved_models")
    
    if not model_dir.exists():
        print(f"❌ 模型目录不存在: {model_dir}")
        return
    
    print(f"📁 模型目录: {model_dir}")
    
    # 检查所有模型文件
    model_files = {
        'lightgbm': model_dir / 'lightgbm_model.pkl',
        'xgboost': model_dir / 'xgboost_model.pkl',
        'mlp': model_dir / 'mlp_model.pkl',
        'ensemble_config': model_dir / 'ensemble_config.json'
    }
    
    for model_name, file_path in model_files.items():
        print(f"\n🤖 检查 {model_name} 模型:")
        
        if file_path.exists():
            file_size = file_path.stat().st_size
            file_time = datetime.fromtimestamp(file_path.stat().st_mtime)
            print(f"  ✅ 文件存在")
            print(f"  📊 文件大小: {file_size:,} 字节")
            print(f"  📅 修改时间: {file_time}")
            
            # 尝试加载模型文件
            try:
                if model_name == 'ensemble_config':
                    with open(file_path, 'r') as f:
                        config = json.load(f)
                    print(f"  📋 配置内容: {config}")
                else:
                    with open(file_path, 'rb') as f:
                        model_data = pickle.load(f)
                    
                    if isinstance(model_data, dict):
                        print(f"  📋 模型类型: {model_data.get('model_type', 'unknown')}")
                        print(f"  📋 输入特征: {model_data.get('input_features', 'unknown')}")
                        print(f"  📋 输出特征: {model_data.get('output_features', 'unknown')}")
                        
                        training_time = model_data.get('training_time')
                        if training_time:
                            if isinstance(training_time, str):
                                training_time = datetime.fromisoformat(training_time.replace('Z', '+00:00'))
                            print(f"  📅 训练时间: {training_time}")
                        
                        # 检查模型对象
                        model = model_data.get('model')
                        if model:
                            model_type = type(model).__name__
                            print(f"  🤖 模型对象类型: {model_type}")
                            
                            # 检查是否是MultiOutputRegressor
                            if hasattr(model, 'estimators_'):
                                print(f"  📊 估计器数量: {len(model.estimators_)}")
                                if len(model.estimators_) > 0:
                                    first_estimator = model.estimators_[0]
                                    print(f"  🤖 第一个估计器类型: {type(first_estimator).__name__}")
                    else:
                        print(f"  📋 模型对象类型: {type(model_data).__name__}")
                        
            except Exception as e:
                print(f"  ❌ 加载模型文件失败: {e}")
        else:
            print(f"  ❌ 文件不存在")
    
    # 检查数据库中的模型评估记录
    print(f"\n📊 检查数据库中的模型评估记录:")
    try:
        from backend.config.database import get_db_session
        from backend.entities.model_eval import ModelEval
        from sqlalchemy import desc
        
        with get_db_session() as db:
            eval_records = db.query(ModelEval).order_by(desc(ModelEval.train_dt)).limit(10).all()
            
            if eval_records:
                print(f"  📋 最近10条评估记录:")
                for record in eval_records:
                    print(f"    📅 {record.train_dt}: {record.model_name} - MAE: {record.mae:.2f}, R²: {record.r2:.4f}")
            else:
                print(f"  ❌ 数据库中没有模型评估记录")
                
    except Exception as e:
        print(f"  ❌ 检查数据库失败: {e}")

if __name__ == "__main__":
    check_model_files()